package com.ruoyi.tongban.service.impl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.tongban.domain.FaceConfig;
import com.ruoyi.tongban.domain.FaceDevice;
import com.ruoyi.tongban.domain.face.PersonData;
import com.ruoyi.tongban.facedetect.domain.PersonDataBody;
import com.ruoyi.tongban.facedetect.domain.WebSocketSessionBody;
import com.ruoyi.tongban.facedetect.utils.SessionCacheBody;
import com.ruoyi.tongban.service.IFaceConfigService;
import com.ruoyi.tongban.service.IFaceDeviceService;
import com.ruoyi.tongban.utils.Base64ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.tongban.mapper.FacePersonMapper;
import com.ruoyi.tongban.domain.FacePerson;
import com.ruoyi.tongban.service.IFacePersonService;

/**
 * 设备注册用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-04-08
 */
@Service
public class FacePersonServiceImpl implements IFacePersonService 
{
    @Autowired
    private FacePersonMapper facePersonMapper;
    
    @Autowired
    private IFaceDeviceService faceDeviceService;
    
    @Autowired
    private IFaceConfigService faceConfigService;
    
    private static final Logger logger = LoggerFactory.getLogger(FaceSignServiceImpl.class);

    /**
     * 查询设备注册用户
     * 
     * @param personId 设备注册用户ID
     * @return 设备注册用户
     */
    @Override
    public FacePerson selectFacePersonById(Long personId)
    {
        return facePersonMapper.selectFacePersonById(personId);
    }

    /**
     * 查询设备注册用户列表
     * 
     * @param facePerson 设备注册用户
     * @return 设备注册用户
     */
    @Override
    public List<FacePerson> selectFacePersonList(FacePerson facePerson)
    {
        return facePersonMapper.selectFacePersonList(facePerson);
    }

    /**
     * 新增设备注册用户
     * 
     * @param facePerson 设备注册用户
     * @return 结果
     */
    @Override
    public int insertFacePerson(FacePerson facePerson)
    {
        facePerson.setCreateTime(DateUtils.getNowDate());
        return facePersonMapper.insertFacePerson(facePerson);
    }

    /**
     * 修改设备注册用户
     * 
     * @param facePerson 设备注册用户
     * @return 结果
     */
    @Override
    public int updateFacePerson(FacePerson facePerson)
    {
    
        FacePerson person = new FacePerson();
        person.setIcCard(facePerson.getIcCard());
        
        List<FacePerson> facePeopleList =  facePersonMapper.selectFacePersonList(person);
        if(facePeopleList.size() != 0){
            return 0;
        }
        
        return facePersonMapper.updateFacePerson(facePerson);
    }

    /**
     * 批量删除设备注册用户
     * 
     * @param personIds 需要删除的设备注册用户ID
     * @return 结果
     */
    @Override
    public int deleteFacePersonByIds(Long[] personIds)
    {
        return facePersonMapper.deleteFacePersonByIds(personIds);
    }

    /**
     * 删除设备注册用户信息
     * 
     * @param personId 设备注册用户ID
     * @return 结果
     */
    @Override
    public int deleteFacePersonById(Long personId)
    {
        return facePersonMapper.deleteFacePersonById(personId);
    }
    
    public FacePerson getDevicePersonDetail(Map<String, Object> paramMap){
        return facePersonMapper.getDevicePersonDetail(paramMap);
    }
    
    @Async
    public void butchAddPeople(String sn){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("sn", sn);
        List<FacePerson> facePeopleList = facePersonMapper.listDevicePersonBySn(paramMap);
        for(FacePerson facePerson : facePeopleList){
            addPeople(facePerson.getPersonId());
        }
    }
    
    
    /**
     * @Description 增加人脸识别数据
     * @Author caiyanshan
     * @Date 2021/4/7 14:31
     * @Param [sn, message]
     * @Return void
     */
    public AjaxResult addPeople(Long personId){
        
        FacePerson facePerson = facePersonMapper.selectFacePersonById(personId);
        Long deptId = facePerson.getDeptId();
        FaceDevice faceDevice = new FaceDevice();
        faceDevice.setDeptId(deptId);
        List<FaceDevice> faceDeviceList = faceDeviceService.selectFaceDeviceList(faceDevice);
        if(faceDeviceList.size() == 0){//不能为0
            return AjaxResult.error("该机构不存在人脸识别设备");
        }
        faceDevice = faceDeviceList.get(0);
        String sn = faceDevice.getSn();
        Gson gson = new Gson();
        PersonDataBody personData = new PersonDataBody();
        PersonDataBody.Person person = new PersonDataBody.Person();
        person.setCmd("addUser");
        person.setUser_id(facePerson.getDevicePersonId());
        person.setName(facePerson.getUserName());
        person.setIc(facePerson.getIcCard());
        person.setId_valid("");//空为此用户永久有效

        //配置考勤权限
        FaceConfig config = new FaceConfig();
        config.setConfigType("faceAuth");
        List<FaceConfig> faceConfigList = faceConfigService.selectFaceConfigList(config);//无配置全天通行
        if(faceConfigList.size() != 0){
            List<Map<String, String>> listParam = new ArrayList<Map<String, String>>();
            Map<String, String> paramMap = null;
            FaceConfig faceConfig = faceConfigList.get(0);
            String faceAuth = faceConfig.getConfigValue();
            String[] faceList = faceAuth.split(",");//按照逗号分隔
            for(String authTime : faceList){
                paramMap = new HashMap<>();
                String[] authTimeList = authTime.split("-");//按照横线分割
                paramMap.put("start_time", authTimeList[0]);
                paramMap.put("end_time", authTimeList[1]);
                listParam.add(paramMap);
            }
            person.setValid_cycle(listParam);
        }
        person.setFace_template(facePerson.getImage());

        personData.setTo(sn);
        personData.setForm("123");
        personData.setCmd("to_device");
        personData.setData(person);
        logger.info(gson.toJson(personData));
        WebSocketSessionBody socketSession = SessionCacheBody.getSession(sn);
        if(socketSession == null){//不可以等于null
            return AjaxResult.error("设备不在线,不可以下放人员数据");
        }
        socketSession.getSession().sendText(gson.toJson(personData));
        
        return AjaxResult.success();
    }
}
